<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="filterState.cate_id" placeholder="请选择分类" size="small">
              <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="filterState.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="filterHandler" type="primary" size="small">筛选</el-button>
            <el-button @click="resetFilterHandler" type="info" size="small">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button @click="pubVisible=true" type="primary" size="small" class="btn-pub">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题">
          <template v-slot="{row}">
            <el-link type="success" @click="showArtDetails(row.id)"> {{row.title}} </el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类"  prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="{row}">
            {{formatDate(row.pub_date)}}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button @click="delArtHandler(row.id)" type="danger" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[2,3,5,10]"
          :page-size="q.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="artTotal">
      </el-pagination>
    </el-card>

      <!-- 发表文章的dialog -->
    <el-dialog
        title="提示"
        :visible.sync="pubVisible"
        fullscreen
        :before-close="handleClose">
        <el-form :model="pubForm" :rules="pubRules" ref="pubForm" label-width="100px" >
            <el-form-item label="文章标题" prop="title" placeholder="请输入文章标题">
                <el-input v-model="pubForm.title"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="cate_id" >
                <el-select v-model="pubForm.cate_id" placeholder="请选择文章分类" style="width:100%">
                    <el-option
                    v-for="item in cateList"
                    :key="item.id"
                    :label="item.cate_name"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
                <quill-editor v-model="pubForm.content"></quill-editor>
            </el-form-item>
            <el-form-item label="文章封面" prop="cover_img">
              <!-- 用来显示封面的图片 -->
              <img :src="artCoverImg" alt="" class="cover-img" ref="imgRef" />
              <br />
              <!-- 文件选择框，默认被隐藏 -->
              <input type="file" @change="coverImgChangeHandler" style="display: none;" accept="image/*" ref="iptFileRef" />
              <!-- 选择封面的按钮 -->
              <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
            </el-form-item>
            <el-form-item prop="state">
              <el-button type="primary" @click="pubArticleHandler('已发布')">发布</el-button>
              <el-button type="danger" @click="pubArticleHandler('草稿')">存为草稿</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 展示文章详情的dialog -->
    <el-dialog title="文章预览" :visible.sync="showDetailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ formatDate(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
// 将静态图片资源作为文件对象导入,动态切换时作为默认图像显示
import coverImg from '../../../assets/images/cover.jpg'
// 引入时间格式化插件
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      filterState: {
        cate_id: '',
        state: ''
      },
      artCoverImg: coverImg,
      pubVisible: false,
      showDetailVisible: false,
      artTotal: 0,
      artDetail: '',
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题需要时1-30位字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'change' }
        ],
        cover_img: [
          { required: true, message: '请选择文章封面', trigger: 'change' }
        ]
      },
      cateList: [],
      artList: []
    }
  },
  methods: {
    // handleClose (done) {
    //   this.$confirm('确认关闭？')
    //     .then(_ => {
    //       done()
    //     })
    //     .catch(_ => {})
    // }
    async handleClose (done) {
      const res = await this.$confirm('未保存就关闭会丢失数据,确认关闭？', '提示')
        .catch(e => e)
      if (res === 'confirm') { done() }
    },
    async getCateList () {
      const { data: res } = await this.$axios.get('/my/cate/list')
      // console.log(res.data)
      if (res.code === 0) {
        this.cateList = res.data
        // console.log(this.cateList)
      }
    },
    coverImgChangeHandler (e) {
      // 触发files的change事件,需要将blob格式文件传递给后台,并将图片文件预览给浏览区域
      if (e.target.files.length === 0) {
        this.$message.error('请选择图片')
        this.pubForm.cover_img = this.artCoverImg
      } else {
        // console.log(e.target.files[0])
        this.pubForm.cover_img = e.target.files[0]
        // 将图片文件传给后台后,将其显示至预览区-->两种方式：1.转base64   2.转URL
        // 1.转base64-->图片比较小才能这么干,封面图比较大,建议转url
        // const fr = new FileReader()
        // fr.readAsDataURL(e.target.files[0])
        // fr.onload = (e) => {
        //   this.artCoverImg = e.target.result
        // }

        // 2.转URL
        const url = URL.createObjectURL(e.target.files[0])
        this.artCoverImg = url
      }
    },
    pubArticleHandler (state) {
      this.$refs.pubForm.validate(async valid => {
        if (!valid) return
        // 表单兜底校验通过,将state状态赋值给data中的pubForm
        this.pubForm.state = state
        // 将pubForm中的数据交给FormData发送给后台
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        // 将携带数据的fd作为参数传递给后台
        const { data: res } = await this.$axios.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭文章添加的dialog-->清空表单(注意图片需要手动清除)
        // this.pubVisible = false
        // this.$refs.pubForm.resetFields()
        // this.artCoverImg = coverImg
        // 添加文章成功后重新获取数据渲染页面
        this.getArtList()
      })
    },
    // 定义获取文章列表数据的函数,每次操作文章数据后需要调用
    async getArtList () {
      const { data: res } = await this.$axios.get('/my/article/list', { params: { ...this.q } })
      if (res.code === 0) {
        this.artList = res.data
        this.artTotal = res.total
        // console.log(this.artTotal)
      }
    },
    formatDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSizeChange (size) {
      // console.log(size)
      this.q.pagesize = size
      this.getArtList()
    },
    handleCurrentChange (page) {
      // console.log(page)
      this.q.pagenum = page
      this.getArtList()
    },
    filterHandler () {
      this.q.cate_id = this.filterState.cate_id
      this.q.state = this.filterState.state
      this.getArtList()
    },
    resetFilterHandler () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.filterState = {
        cate_id: '',
        state: ''
      }
      this.getArtList()
    },
    async delArtHandler (id) {
      console.log(id)
      // 给用户提示信息
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
        // 发送请求删除数据,更新页面
        const { data: res } = await this.$axios.delete('/my/article/info', { params: { id } })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 删除数据时有小bug：
        // 1.当删除的数据是最后一页的最后一条时,页面数据会消失-->发送请求的页码数还是最后一页,需要自减一
        // 2.进行判定-->完成最后一页最后一条数据删除时页码自减一,删除到第一页最后一条会报错-->最后一条不自剪
        if (this.artList.length === 1 && this.q.pagenum > 1) this.q.pagenum--
        // console.log(this.artList)
        this.getArtList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async showArtDetails (id) {
      // console.log(id)
      const { data: res } = await this.$axios.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return
      this.artDetail = res.data
      console.log(this.artDetail)
      this.showDetailVisible = true
    }
  },
  created () {
    this.getCateList()
    this.getArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
</style>
